<!--
 * @Author: cest cestrmail@163.com
 * @Date: 2022-12-12 16:05:51
 * @LastEditors: cest cestrmail@163.com
 * @LastEditTime: 2022-12-13 16:12:18
 * @FilePath: /ithome-lite/src/pages/detail/news.vue
 * @Description: 文章详情
-->
<template>
  <div class="container theme">
    <div class="header">
      <h1 class="news-title">{{ title }}</h1>
      <div class="auth-info" v-if="news">{{ news.newssource }}({{ news.newsauthor }})</div>
    </div>
    <div class="news-content" v-html="news?.detail"></div>
    <h2 class="related-title" v-if="relatedNews.length">相关文章</h2>
    <div class="news-wrap">
      <NewsItem v-for="news of relatedNews" :news="news" :key="news.id"></NewsItem>
    </div>
  </div>
</template>

<script lang="ts" setup>
import xml2json from 'xmlstring2json'
import NewsItem from '@/components/NewsItem.vue'
import { getNews } from '@/utils/api'
import { onMounted, reactive, ref } from 'vue'

const relatedNews: Array<ComponentModels.NewsItem> = reactive([])
interface Props {
  id: string
  title: string
}
const props = defineProps<Props>()

/**
 * 获取新闻详情
 */

const news = ref<{
  /** 文章来源 */
  newssource: string
  /** 文章详情 */
  detail: string
  /** 作者 */
  newsauthor: string
}>()

const getNewsAsync = async () => {
  const _id = `${id.value.slice(0, 3)}/${id.value.slice(3, 6)}`
  const _news = await getNews(_id)
  if (!_news) return
  const parsedNews: ResponseDataModels.NewsDetail = xml2json(_news).rss.channel.item
  news.value = {
    newssource: parsedNews.newssource['#text'],
    detail: parsedNews.detail['#text'].replace(/<img/g, '<img width="100%"'),
    newsauthor: parsedNews.newsauthor['#text']
  }
  console.log('getNewsAsync:', news.value)
}

/**
 * 获取相关文章列表
 */
const getRelatedNews = async () => {}

/**
 * 页面初始化
 */
const id = ref()
const title = ref('')
const init = async () => {
  id.value = props.id
  title.value = props.title
  console.log('init:', { id: id.value, title: title.value })
  uni.showNavigationBarLoading()
  await Promise.all([getNewsAsync(), getRelatedNews()])
  uni.hideNavigationBarLoading()
}

init()
</script>

<style lang="scss">
@import '@/assets/styles/index.scss';

.header {
  width: 100%;
  color: #fff;
  background-color: var(--primary-color);
  padding: 10px;
  box-sizing: border-box;
}

.news-title {
  font-size: 22px;
}

.auth-info {
  font-size: 12px;
  margin-top: 10px;
  text-align: right;
}

.news-content {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
  line-height: 1.6;
}
</style>
